#include "Common.h"
#include "SystemV/AppLibSystemV_Shm.hpp"

#include <sys/ipc.h>

/**********************************************************
 * Function Name:        AppLibSystemV_ShmCreate
 * Description:          消息初始化
 * Parameters[in]:       IN CHAR *pcFilePath
 *                       INOUT SINT32 *piQueueId
 * Parameters[out]:      INOUT SINT32 *piQueueId
 * ReturnValue:          ULONG
 * Author:               liuke
 * Date:                 2024.04.16
***********************************************************/
ULONG AppLibSystemV_ShmCreate(IN CHAR *pcFilePath, IN size_t size, INOUT SINT32 *piQueueId)
{
    SINT32 iFd = 0;

    if ((pcFilePath == NULL) || (piQueueId == NULL))
    {
        LOG_ERROR("err: pcFilePath=%p piQueueId=%p\n", pcFilePath, piQueueId);
        return STAT_ERR_INVAILD_PARAM;
    }

    iFd = AppLibSystemV_Get(APP_LIB_SYSTEM_V_TYPE_SHM, pcFilePath, size);
    if(iFd < 0)
    {
        LOG_ERROR("err %d [%s]\n", errno, strerror(errno));
        return STAT_ERR_SYSTEM_V_SHM_GET;
    }

    *piQueueId = iFd;

    return STAT_SUCCESS;
}

/**********************************************************
 * Function Name:        SystemV_Shm_Destory
 * Description:          消息注销
 * Parameters[in]:       INOUT SINT32 *piQueueId
 * Parameters[out]:      INOUT SINT32 *piQueueId
 * ReturnValue:          ULONG
 * Author:               liuke
 * Date:                 2024.04.16
***********************************************************/
ULONG AppLibSystemV_ShmDestory(INOUT SINT32 *piQueueId)
{
    if ((piQueueId == NULL) || (*piQueueId < 0))
    {
        LOG_ERROR("Shm already destory\n");
        return STAT_ERR_INVAILD_PARAM;
    }

    AppLibSystemV_Ctl(APP_LIB_SYSTEM_V_TYPE_SHM, *piQueueId, IPC_RMID, 0);

    *piQueueId = -1;

    return STAT_SUCCESS;
}

/**********************************************************
 * Function Name:        SystemV_Shm_Attach
 * Description:          消息发送
 * Parameters[in]:       IN SINT32 iQueueId
                         INOUT void **pAddr
 * Parameters[out]:      INOUT void **pAddr
 * ReturnValue:          ULONG
 * Author:               liuke
 * Date:                 2024.04.16
***********************************************************/
ULONG AppLibSystemV_ShmAttach(IN SINT32 iQueueId, IN void **ppAddr)
{
    return AppLibSystemV_ShmCtrl(APP_LIB_SYSTEM_V_SHM_OP_AT, iQueueId, ppAddr);
}

/**********************************************************
 * Function Name:        AppLibSystemV_ShmDetach
 * Description:
 * Parameters[in]:       INOUT void **pAddr
 * Parameters[out]:      INOUT void **pAddr
 * ReturnValue:          ULONG
 * Author:               liuke
 * Date:                 2024.04.16
***********************************************************/
ULONG AppLibSystemV_ShmDetach(INOUT void *pAddr)
{
    return AppLibSystemV_ShmCtrl(APP_LIB_SYSTEM_V_SHM_OP_DT, pAddr);
}
